<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title></title>
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0" />
    <link rel="stylesheet" href="/layuiadmin/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="/layuiadmin/style/admin.css" media="all" />
    <link rel="stylesheet" href="/layuiadmin/style/live_chat.css?v={:config('other.ui_version')}" media="all" />
</head>

<body>
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-tab layui-tab-brief">
                <ul class="layui-tab-title layui_tab_title">
                    <li class=""><a href="/admin/live/dashboard">直播视频监控</a></li>
                    <li class=""><a href="/admin/chat/log">用户聊天日志</a></li>
                    <li class="layui-this"><a href="/admin/chat/live_chat">直播间聊天监控</a></li>
                </ul>
            </div>

            <div class="layui-card-body">
                <hr />
                <div>
                    <input name="pub_content_all" id="pub_content_all" size="80"
                        style="border:1px solid #ccc;height:25px;margin-top:10px;" type="text">
                    <button class="layui-btn layui-btn-xs layui-btn-normal" onclick="javascript:pub_all();">回复所有</button>
                </div>
                <hr />
                <div class="layui-row layui-col-space10" id="liveChatArea">
                    {volist name='lives' id='live'}
                    <div class="layui-col-md3">
                        <div class="layui-card live_chat_info">
                            <div class="room_user">
                                <strong>{$live.anchor.nick_name|default=''}({$live.anchor.id|default=''})的直播间</strong>
                                <span class="refreshChat">
                                    <i class="layui-icon layui-icon-refresh-1"></i>
                                    刷新
                                </span>
                            </div>
                            <ul class="chat_list chatList" id="chatLog{$live.anchor.id}"
                                data-anchor="{$live.anchor.id|default=''}" data-chatkey="{$i}">
                                <li class="chat_loading"><i
                                        class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i>
                                </li>
                            </ul>
                            <div id="chatLogUpTime{$live.anchor.id}" class="up_time">更新时间：<span></span></div>
                        </div>
                        <div>
                            <input name="pub_name_{$live.anchor.id}" id="pub_name_{$live.anchor.id}" value="{:Lang('reply_nickname')}" size="10"
                                style="border:1px solid #ccc;height:25px;margin-top:10px;" type="text">
                            <input name="pub_content_{$live.anchor.id}" id="pub_content_{$live.anchor.id}" size="35"
                                style="border:1px solid #ccc;height:25px;margin-top:10px;" type="text">
                            <br />
                            <button class="layui-btn layui-btn-xs layui-btn-normal" onclick="javascript:pub({$live.anchor.id});">回复</button>
                        </div>
                    </div>
                    {/volist}
                </div>
                <div id="pager" style="margin-top: 20px;margin-left: 20px;"></div>
            </div>
        </div>
    </div>

    <script src="/layuiadmin/layui/layui.js"></script>
    <script src="/assets/ue/third-party/jquery-1.10.2.js"></script>
    <script>
        layui.config({
            base: '/layuiadmin/' //静态资源所在路径
            , version: "{:config('other.ui_version')}"
        }).extend({
            index: 'lib/index' //主入口模块
        }).use(['index', 'table', 'admin', 'laypage'], function () {
            var admin = layui.admin;
            var laypage = layui.laypage;

            //执行一个laypage实例
            laypage.render({
                elem: 'pager'
                , curr: {$page}
                , count: {$count}
                , limit: {$limit}
                , layout: ['prev', 'page', 'next', 'skip', 'count']
                , jump: function (obj, first) {
                    if (!first) {
                        window.location.href = '{:url("chat/live_chat")}?page=' + obj.curr;
                    }
                }
            });


            /**
             * 日志列表获取
             * @param room_id 房间/主播id
             * @param chat_time 聊天日志最新一条的时间
             * @param chat_key 页面data-chatkey值
             * @param is_refresh 是否手动刷新
             */
            function getLiveChat(room_id, chat_time, chat_key, is_refresh) {
                // 如果正在手动刷新则不更新
                if ($('#chatLog' + room_id).data('refresh') == 1) {
                    return false;
                }

                if (is_refresh == 1) {
                    $('#chatLog' + room_id).data('refresh', 1);
                }

                $.ajax({
                    url: '{:url("chat/get_live_chat")}',
                    type: 'get',
                    data: { room_id: room_id, chat_time: chat_time },
                    dataType: 'json',
                    success: function (res) {
                        var chat_data = res.data;
                        if (chat_data.length > 0) {
                            // 获取某一个聊天室区域下已经展示的消息id
                            let chat_ids_arr = getLiveChatIds(room_id);

                            var html = '';
                            $.each(chat_data, function (i, val) {

                                // 消息排重，重复的消息id不显示在页面上
                                let is_show_msg = true;
                                for (let ii = 0; ii <= chat_ids_arr.length; ii++) {
                                    if (val.id == chat_ids_arr[ii]) {
                                        is_show_msg = false;
                                    }
                                }
                                if (is_show_msg == false) {
                                    return true;
                                }

                                var content = val.content;
                                html += `<li data-id="${val.id}" data-time="${val.create_time}" data-uid="${val.user_id}" data-nickname="${val.nick_name}" data-bannedid="${val.bannedid}" data-content="${content}" data-timestr="${val.create_time_str}">`;
                                html += `</li>`

                            });
                            $('#chatLog' + room_id).find('.chat_loading').remove();
                            $('#chatLog' + room_id).prepend(html);

                        } else {
                            var li_len = $('#chatLog' + room_id).find('li:not(.chat_loading)').length;
                            if (li_len <= 0) {
                                $('#chatLog' + room_id).find('.chat_loading').html('暂无聊天内容');
                            }
                        }

                        // 设置屏蔽和禁言
                        updateChatInfo(room_id, res.band_user, res.shield);

                        // 重置手动刷新
                        $('#chatLog' + room_id).data('refresh', 0);
                        $('#chatLogUpTime' + room_id).find('span').text(res.uptime);
                    }
                });
            }

            /**
             * 设置消息，主要是屏蔽消息和禁言用户
             * @param room_id 房间id
             * @param band_user 禁言用户
             * @param shield_data 屏蔽发言id数组
             */
            function updateChatInfo(room_id, band_user, shield_data) {
                $.each($('#chatLog' + room_id + ' li'), function (i, val) {
                    var li_obj = $(this);
                    if (!li_obj.data('uid')) {
                        return false;
                    }
                    // 聊天内容
                    var content = li_obj.data('content');
                    // 消息id
                    var msg_id = li_obj.data('id');
                    // 用户id
                    var user_id = li_obj.data('uid');
                    // 用户昵称
                    var user_nick_name = li_obj.data('nickname');
                    // 消息创建时间
                    var create_time_str = li_obj.data('timestr');
                    // 是否屏蔽了发言 0 屏蔽 1=未屏蔽
                    var is_shield = 1;
                    // 禁言状态 1=正常 2被禁言
                    var band_status = 1;
                    // 禁言信息
                    var band_info = null;
                    var html = '';


                    $.each(shield_data, function (si, sh_val) {
                        if (sh_val == msg_id) {
                            is_shield = 0;
                        }
                    })

                    $.each(band_user, function (bi, ban_val) {
                        if (ban_val.uid == user_id) {
                            band_status = 2;
                            band_info = ban_val;
                        }
                    })

                    if (is_shield == 1) {
                        content = '<em class="shield shieldSpeak">' + content + '</em>';
                    }

                    if (band_info) {
                        if (band_info.mgrid == 0) {
                            html += `<span><i>${band_info.mgrname}</i>:</span>`;
                            content = '【<em class="unBanned shield">' + user_nick_name + '</em>】已被禁言，聊天内容：' + content;
                        } else {
                            html += `<span><i>房管</i>${band_info.mgrname}:</span>`
                            content = '【<em class="unBanned shield">' + user_nick_name + '</em>】已被禁言，聊天内容：' + content;
                        }
                        li_obj.data('bannedid', band_info.bannedid);
                    } else {
                        html += `<span class="bannerdBtn shield">${user_nick_name}:</span>`
                        li_obj.data('bannedid', 0);
                    }


                    // 是否屏蔽了发言 status 0屏蔽了发言 1未屏蔽
                    if (is_shield != 1) {
                        html += `<em class="${band_status == 2 ? 'red' : ''} ">${content}</em><em style="color:#FFB800">【已屏蔽】</em><i>${create_time_str}</i>`
                    } else {
                        html += `<em class="${band_status == 2 ? 'red' : ''}">${content}</em><i><button class="layui-btn layui-btn-xs layui-btn-normal" onclick="javascript:reply(${room_id}, '${user_nick_name}');">回复</button> ${create_time_str}</i>`
                    }

                    li_obj.html(html)
                })
            }

            /**
             * 禁言用户
             */
            $(document).on('click', '.chatList .bannerdBtn', function () {
                let uid = $(this).parents('li').eq(0).data('uid');
                let chat_id = $(this).parents('li').eq(0).data('id');
                let room_id = $(this).parents('ul').eq(0).data('anchor');
                if (uid < 1) {
                    return layer.msg('用户信息错误，请刷新页面', { icon: 5 });
                }
                layer.open({
                    type: 2,
                    title: "确定禁言该用户吗?",
                    content: "{:url('user/setBanTime')}?type=3&id=" + uid + '&room_id=' + room_id + '&chat_id=' + chat_id,
                    maxmin: true,
                    area: ["700px", "530px"],
                });
            })

            /**
             * 屏蔽发言
             */
            $(document).on('click', '.chatList .shieldSpeak', function () {
                let id = $(this).parents('li').eq(0).data('id');
                let room_id = $(this).parents('ul').eq(0).data('anchor');
                if (id < 1) {
                    layer.msg('信息错误，请刷新页面', { icon: 5 });
                }
                layer.open({
                    type: 2,
                    title: "确定屏蔽该发言内容吗?",
                    content: "{:url('chat/shield')}?id=" + id + '&room_id=' + room_id,
                    maxmin: true,
                    area: ["500px", "450px"],
                });
            })

            /**
             * 解除禁言
             */
            $(document).on('click', '.chatList .unBanned', function () {
                let bannedid = $(this).parents('li').eq(0).data('bannedid');
                let uid = $(this).parents('li').eq(0).data('uid');
                let room_id = $(this).parents('ul').eq(0).data('anchor');
                if (bannedid < 1 || uid < 1) {
                    layer.msg('用户信息错误，请刷新页面', { icon: 5 });
                }
                layer.confirm("确定解除禁言？", function (index) {
                    layer.load();
                    admin.req({
                        url: "{:url('user/unBanned')}",
                        data: { id: bannedid, room_id: room_id },
                        success(res) {
                            if (res.code == 0) {
                                layer.msg(res.msg, { icon: 1, time: 2000 }, function () {
                                    window.location.reload();
                                });
                            }
                            layer.closeAll("loading");
                        },
                        complete: function () {
                            layer.closeAll("loading");
                        },
                    });
                });
            })

            /**
             * 获取聊天区域的所有消息id
             */
            function getLiveChatIds(room_id) {
                let chat_ids = new Array();
                $('#chatLog' + room_id).find('li').each(function (i, val) {
                    let id = $(val).data('id');
                    let ss = /^\+?[1-9][0-9]*$/;　　//判断是否为正整数
                    if (ss.test(id)) {
                        chat_ids[i] = id;
                    }
                })
                return chat_ids;
            }


            /**
             * 加载每个直播的聊天信息
             */
            function liveChatOperation() {
                var chat_list_len = $('#liveChatArea .chatList').length;
                for (var i = 0; i < chat_list_len; i++) {
                    // dom对象节点
                    var chat_list_obj = $('#liveChatArea .chatList').eq(i)
                    // 页面上序号
                    var chatkey = chat_list_obj.data('chatkey');
                    // 直播/房间id
                    var anchor = chat_list_obj.data('anchor');
                    // 聊天最新获取的时间点
                    var chat_time = chat_list_obj.find('li:first-child').data('time');

                    if (chat_time == 0) {
                        getLiveChat(anchor, 0, chatkey, 0);
                    } else {
                        getLiveChat(anchor, chat_time, chatkey, 0);
                    }
                }
            }


            $('.refreshChat').click(function () {
                let chat_list_obj = $(this).parents('.live_chat_info').find('.chatList');
                let chatkey = chat_list_obj.data('chatkey');
                let anchor = chat_list_obj.data('anchor');
                // 设置加载代码
                chat_list_obj.html('<li class="chat_loading"><i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i></li>');
                // 加载聊天内容
                getLiveChat(anchor, 0, chatkey, 1);
            })


            liveChatOperation();

            // 5秒更新一次聊天
            setInterval(function () {
                liveChatOperation();
            }, 5000);


            // // 鼠标经过气泡显示
            // var tips;
            // $(document).on({
            //     mouseenter: function () {
            //         var that = this;
            //         tips = layer.tips("点击可操作", that, {tips:3});
            //     },
            //     mouseleave: function () {
            //         layer.close(tips);
            //     }
            // }, '.chatList .shield');
        });

        function pub(id) {
            let content = $("#pub_content_" + id).val()
            let name = $("#pub_name_" + id).val()
            if (content.length <= 0) {
                return layer.msg('请输入内容', { icon: 5 });
            }
            $.ajax({
                url: '/admin/chat/admin_pub',
                type: 'get',
                data: { room_id: id, content: content, name: name },
                dataType: 'json',
                success: function (res) {
                    // 重置手动刷新
                    $('#chatLog' + id).data('refresh', 0);
                    // $('#chatLogUpTime' + id).find('span').text(res.uptime);
                    $("#pub_content_" + id).val('')
                    layer.msg('发送成功', { icon: 1 });
                }
            });
        }

        function pub_all(id) {
            let content = $("#pub_content_all").val()
            if (content.length <= 0) {
                return layer.msg('请输入内容', { icon: 5 });
            }
            $.ajax({
                url: '{:url("chat/admin_pub_all")}',
                type: 'get',
                data: { room_id: id, content: content },
                dataType: 'json',
                success: function (res) {
                    // 重置手动刷新
                    $("#pub_content_all").val('')
                    layer.msg('发送成功', { icon: 1 });
                }
            });
        }

        function reply(room_id, name) {
            layer.open({
                type: 2,
                title: "回复用户: " + name,
                content: '/admin/chat/reply?room_id='+room_id+'&user='+name,
                maxmin: true,
                area: ["600px", "430px"],
            });
        }

    </script>
</body>

</html>